<template>
  <div class="erwei">
    <div class="img" v-loading="loading">
      <img width="200px" alt="" :src="qrimg" />
      <i class="mask" v-if="showQrMask" :style="maskBg" @click="updateQr"></i>
    </div>
    <p>
      <span class="iconfont icon-weixin"></span>
      <b>扫描二维码</b>
    </p>
  </div>
</template>
<script>
import socketIo from "socket.io-client";
import qrcode from "qrcode";
// 引入api
import * as api from "../../api/users";
//引入扫码成功或者失败的遮罩图片
import invalidImg from "../../assets/img/invalidQr.png";
import scanSuccessImg from "../../assets/img/scancode.png";
import storage from "../../utils/storage";
export default {
  props: ["storageUserInfo"],
  data() {
    return {
      qrimg: "",
      showQrMask: false,
      maskBg: { background: `url(${scanSuccessImg})` },
      loading: true,
    };
  },
  created() {
    // 建立socketio链接
    // console.log(this.storageUserInfo);
    let io = socketIo("wss://chst.vip");
    //监听socket事件
    io.on("connectSuccess", async ({ sid }) => {
      // 请求获取二维码图片
      storage.set("qf-sid", sid);
      this.getQrUrl(sid);
    });
    //二维码失效时的样式
    io.on("invalidCode", (data) => {
      this.showQrMask = true;
      this.maskBg.background = `url(${invalidImg})`;
    });
    //扫码成功的样式
    io.on("scancodeSuccess", async ({ wechatCode, state, msg }) => {
      //   console.log(data);
      this.showQrMask = true;
      this.maskBg.background = `url(${scanSuccessImg})`;
      if (state) {
        let res = await api.wechatLoginApi(wechatCode);
        this.storageUserInfo(res.data);
        this.$router.push("/");
        // console.log(res);
      } else {
        console.error(msg);
      }
    });
  },
  methods: {
    async getQrUrl(sid) {
      let res = await api.getQrCodeApi(sid);
      //   console.log(res);
      let { scanCodeUrl } = res.data;
      // 生成二维码之前loading显示
      this.loading = true;
      //   通过qrcode插件才能生成二维码
      qrcode.toDataURL(scanCodeUrl, (err, img) => {
        if (err) {
          throw err;
        }
        this.qrimg = img;
        this.showQrMask = false;
      });
      //生成以后关闭loading
      this.loading = false;
    },
    updateQr() {
      let sid = storage.get("qf-sid");
      this.getQrUrl(sid);
      //   console.log(sid);
    },
  },
};
</script>
<style lang="less" scoped>
.erwei {
  margin-left: 125px;
  background-color: #fff;
  width: 200px;
  height: 200px;
}
.img {
  position: absolute;
  top: 280px;
  right: 254px;
}
img {
  position: absolute;
  top: -95px;
  right: 0;
  left: -84px;
  bottom: 0;
}
b {
  position: absolute;
  top: 400px;
  right: 174px;
}
.icon-weixin {
  font-size: 25px;
  position: absolute;
  top: 400px;
  right: 257px;
}
.mask {
  width: 204px;
  height: 200px;
  opacity: 0.6;
  background-color: white;
  position: absolute;
  top: -95px;
  left: -84px;
  right: 0;
  bottom: 0;
  z-index: 122;
}
</style>
